import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:rembercount/pages/main_page.dart';

class Authlogincontroller extends GetxController {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final formKey = GlobalKey<FormState>();
  var isLogin = false.obs;
  var isObscure = true.obs;
  final phoneController = TextEditingController();
  static const String _loginKey = 'isLoggedIn';
  static const String _loginTimeKey = 'loginTime';
  static const String _emailKey = 'email';
  static const String _phoneKey = 'phone';
  static const String _reFundKey = 'preFund';
    double preFund = 0;
  static const int _loginValidDays = 30; // 修改为30天
  final dio = Dio(BaseOptions(
    baseUrl: const String.fromEnvironment('BASE_URL', defaultValue: "http://localhost:8080"),
  ));

  @override
  void onInit() {
    super.onInit();
    _loadLoginState();
  }

  Future<void> init() async {
    await _loadLoginState();
  }

  Future<void> _loadLoginState() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final isLoggedIn = prefs.getBool(_loginKey) ?? false;
      final loginTimeStr = prefs.getString(_loginTimeKey);
      final savedEmail = prefs.getString(_emailKey);
      final savedPhone = prefs.getString(_phoneKey);
      if (isLoggedIn && loginTimeStr != null && savedEmail != null) {
        final loginTime = DateTime.parse(loginTimeStr);
        final now = DateTime.now();
        final difference = now.difference(loginTime).inDays;

        if (difference < _loginValidDays) {
          emailController.text = savedEmail;
          
          isLogin.value = true;
          print('Login state restored: $savedEmail');
          
          // 确保在主页面
           // 验证登录状态是否仍然有效
          try {
            var res = await dio.post("/verifyLogin", data: {
              'email': savedEmail,
            });
            phoneController.text = savedPhone??'';
            print('phoneController.text: ${phoneController.text}');
            print('Verify login response data: ${res.data}'); // 打印完整响应数据
            
            if (res.data['code'] != 200) {
              // 如果验证失败，清除登录状态
              await _clearLoginState();
              return;
            }
          } catch (e) {
            print('Error verifying login: $e');
            // 如果验证出错，保持登录状态
          }
        } else {
          // 登录已过期，清除登录状态
          await _clearLoginState();
        }
      } else {
        await _clearLoginState();
      }
    } catch (e) {
      print('Error loading login state: $e');
      await _clearLoginState();
    }
  }

  Future<void> _clearLoginState() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_loginKey);
    await prefs.remove(_loginTimeKey);
    await prefs.remove(_emailKey);
    isLogin.value = false;
    emailController.clear();
    passwordController.clear();
  }

  void togglePasswordVisibility() {
    isObscure.value = !isObscure.value;
  }
  Future<Map<String, dynamic>> editInfo(var data) async {
    try {
      var res = await dio.post("/editInfo", data: {
        'bio': data['bio'],
        'phone': data['phone'],
//         'email': data['nickname'],
//         '_id': id.value
      });
      
      return res.data;
    } catch (e) {
      print('Error updating profile: $e');
      return {
        'code': 500,
        'msg': '更新失败: $e'
      };
    }
  }

  Future<void> saveLoginStatus() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool(_loginKey, true);
      await prefs.setString(_loginTimeKey, DateTime.now().toIso8601String());
      await prefs.setString(_emailKey, emailController.text);
      await prefs.setString(_phoneKey, phoneController.text);
      await prefs.setDouble(_reFundKey, preFund);
      isLogin.value = true;
      print('Login state saved: ${emailController.text}');
      print('phoneController.text: ${phoneController.text}');
    } catch (e) {
      print('Error saving login state: $e');
    }
  }

  Future<void> logout() async {
    await _clearLoginState();
  }
  Future<void> setPreFund()async{
    final prefs = await SharedPreferences.getInstance();
    var res= await dio.post('/setPreFund',data:{
       'email':prefs.getString(_emailKey),
      'preFund':preFund
     });
     if(res.data['code']==200){
        Get.snackbar("设置预算成功", '');
     }else{
      Get.snackbar("设置预算失败", '');
     }
  }

  Future<double> getPreFund() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final email = prefs.getString(_emailKey);
      if (email == null) return 0.0;
      
      var res = await dio.get('/getPreFund/$email');
      if (res.data['code'] == 200) {
        return (res.data['data'] as num).toDouble();
      } else {
        return 0.0;
      }
    } catch (e) {
      print('Error getting preFund: $e');
      return 0.0;
    }
  }
  Future<void> login() async {
    try {
      var res = await dio.post("/login", data: {
        'email': emailController.text,
        'password': passwordController.text,
      });

      if (res.data['code'] == 200) {
        // 保存登录状态
        await saveLoginStatus();

        // 清除所有路由并跳转到主页
        await Get.offAll(() => const MainPage());
        
        // 显示成功提示
        Get.snackbar(
          '成功',
          '登录成功',
          backgroundColor: const Color(0xFF2D9596).withOpacity(0.1),
          colorText: const Color(0xFF2D9596),
          duration: const Duration(seconds: 2),
        );
      } else {
        Get.snackbar(
          '失败',
          res.data['msg'] ?? '登录失败',
          backgroundColor: Colors.red.withOpacity(0.1),
          colorText: Colors.red,
          duration: const Duration(seconds: 2),
        );
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '登录失败: $e',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
    }
  }

  @override
  void onClose() {
    emailController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}